package com.tanhua.app.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.commons.utils.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class UserFreezeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //根据用户id和冻结范围判断对应的冻结是否存在
    //如果存在冻结数据,抛异常,用户就不能继续操作
    // freezingRange(冻结范围)：  1-冻结登录，2-冻结发言，3-冻结发布动态
    public void freezeCheck(Long userId,String freezingRange){
        //1.获取redis中的冻结数据
        String json = redisTemplate.opsForValue().get(Constants.USER_FREEZE + userId);

        //判断冻结数据是否存在
        if (StringUtils.isNotBlank(json)){
            //如果不是空,则说明有冻结数据
            Map map = JSON.parseObject(json, Map.class);
            String redisFreezingRange = map.get("freezingRange").toString();
            if (freezingRange.equals(redisFreezingRange) && freezingRange.equals("1")){
                throw new BusinessException(ErrorResult.freezeLoginError());
            }
            if (freezingRange.equals(redisFreezingRange) && freezingRange.equals("2")){
                throw new BusinessException(ErrorResult.freezeSpeakError());
            }
            if (freezingRange.equals(redisFreezingRange) && freezingRange.equals("3")){
                throw new BusinessException(ErrorResult.freezeMovementError());
            }
        }
    }
}
